package com.gator.spring.framework.webmvc.servlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.RandomAccessFile;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author PABLO
 * @Date 2022/5/8 13:48
 * @Desc 视图
 */
public class PABLO_View {
    //Context-Type
    public final String DEFAULT_CONTENT_TYPE = "text/html;charset=utf-8";
    public final String CHARACTER_ENCODING = "UTF-8";

    private File viewFile;

    public PABLO_View(File viewFile) {
        this.viewFile = viewFile;
    }

    /**
     * @Description: 渲染,直接输出了
     * @Author: PABLO
     * @Date: 2022/5/8 13:51
     * @Params: [model, request, response]
     * @Return: void
     **/
    public void render(Map<String, ?> model,
                       HttpServletRequest request, HttpServletResponse response) throws Exception{
        StringBuffer sb = new StringBuffer();

        //设置访问返回的页面文件
        RandomAccessFile ra = new RandomAccessFile(this.viewFile,"r");

        String line  = null;
        //读取每一行
        while (null != (line = ra.readLine())){
            line = new String(line.getBytes("ISO-8859-1"),"utf-8");
            //正则，只要该行包含指定表达式，就会填充
            Pattern pattern = Pattern.compile("￥\\{[^\\}]+\\}",Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(line);
            while (matcher.find()){
                String paramName = matcher.group();//返回匹配的位置
                paramName = paramName.replaceAll("￥\\{|\\}","");//取出文件中对应的占位符名称  如￥{teacher}，取出teacher
                Object paramValue = model.get(paramName);
                if(null == paramValue){ continue;}
                line = matcher.replaceFirst(makeStringForRegExp(paramValue.toString()));
                matcher = pattern.matcher(line);
            }
            sb.append(line);//填充后保存源文件的内容
        }

        response.setCharacterEncoding(CHARACTER_ENCODING);
        response.getWriter().write(sb.toString());
    }

    //处理特殊字符
    public static String makeStringForRegExp(String str) {
        return str.replace("\\", "\\\\").replace("*", "\\*")
                .replace("+", "\\+").replace("|", "\\|")
                .replace("{", "\\{").replace("}", "\\}")
                .replace("(", "\\(").replace(")", "\\)")
                .replace("^", "\\^").replace("$", "\\$")
                .replace("[", "\\[").replace("]", "\\]")
                .replace("?", "\\?").replace(",", "\\,")
                .replace(".", "\\.").replace("&", "\\&");
    }
}
